package no.kolstad.movies.controller;


/**
 *  Copyright [2008] Christopher Kolstad
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software distributed under the License 
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License. 
 */

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import no.kolstad.movies.dao.RoleDAO;
import no.kolstad.movies.dao.UserDAO;
import no.kolstad.movies.editor.RoleEditor;
import no.kolstad.movies.model.Role;
import no.kolstad.movies.model.User;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/** 
 *
 * @author chriswk
 */
public class EditUserController extends SimpleFormController {
    private UserDAO uDao;
    private RoleDAO rDao;
    private RoleEditor roleEditor;
    
    public void setUserDAO(UserDAO dao) {
        this.uDao = dao;
    }
    
   
    public void setRoleDAO(RoleDAO dao) {
        this.rDao = dao;
    }
    
    public void setRoleEditor(RoleEditor editor) {
        this.roleEditor = editor;
    }
    protected Log log = LogFactory.getLog(this.getClass());
    
    protected Object formBackingObject(HttpServletRequest request)
      throws Exception {

    if (log.isInfoEnabled()) {
      log.info("EditMovieeController formBackingObject");
    }

    if (request.getParameter("user_id") != null
        && !"".equals(request.getParameter("user_id"))) {
      Long id = Long.parseLong(request.getParameter("user_id"));
      User existingUser = uDao.get(id);
      return existingUser;
    }

    return new User();
    }
    
    protected Map referenceData(HttpServletRequest request,
                                Object command,
                                Errors errors) {
        if(log.isInfoEnabled()) {
            log.info("EditUserController referenceData");
        }
        
        Map<Object, Object> referenceData = new HashMap<Object, Object>();
        
        List<Role> roles = rDao.loadAll();
        
        Iterator<Role> iter = roles.iterator();
        
        Map<Long, String> roleMap = new LinkedHashMap<Long, String>();
        
        while(iter.hasNext()) {
            Role aRole = iter.next();
            if(!aRole.getRolename().equals("ROLE_ROOT")) {
                roleMap.put(aRole.getId(), aRole.getDisplayname());
            }
        }
        
        if(log.isDebugEnabled()) {
            log.debug(new ToStringBuilder(this)
                    .append("Roles")
                    .append(roleMap)
                    .toString());
        }
        
        referenceData.put("roles", roleMap);
        
        return referenceData;
    }
    
    @Override
    public ModelAndView onSubmit(HttpServletRequest request,
      HttpServletResponse response, Object command, BindException errors)
      throws ServletException {
        
      User newuser = (User) command;
      
      uDao.save(newuser);
      
      request.getSession().setAttribute("statusMessage", "User saved");
      return new ModelAndView(new RedirectView(getSuccessView()));
    }
   
    
    protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) 
        throws Exception {
        binder.registerCustomEditor(Set.class, "roles", roleEditor);
        
    }
}